package news;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class Rss_handle extends DefaultHandler{

	private List<Rss_item> rss;
	private Rss_item cur_rss;
	private boolean title;
	private boolean link;
	private boolean des;
	private boolean pub;
	private StringBuffer sb;
	
	public Rss_handle(){
		rss=new ArrayList<Rss_item>();
	}
	public List<Rss_item> getItems(){
		return rss;
	}
	
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		// TODO Auto-generated method stub
		if(title){
			if(cur_rss!=null){
				sb.append(new String(ch,start,length));
			}
		}else if(link){
			if(cur_rss!=null){
				cur_rss.setLink(new String(ch,start,length));
				link=false;
			}
		}
		else if(des){
			if(cur_rss!=null){
				cur_rss.setDes(new String(ch,start,length));
				des=false;
			}
		}else if(pub){
			if(cur_rss!=null){
				cur_rss.setPubdate(new String(ch,start,length));
				pub=false;
			}
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		// TODO Auto-generated method stub
		if("item".equals(qName)){
			rss.add(cur_rss);
			cur_rss=null;
		}else if("title".equals(qName)){
			title=false;
			if(cur_rss!=null){
				cur_rss.setTitle(sb.toString());
			}
		}else if("link".equals(qName)){
			link=false;
		}else if("description".equals(qName)){
			des=false;
		}else if("pubDate".equals(qName)){
			pub=false;
		}
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		// TODO Auto-generated method stub
		if("item".equals(qName)){
			cur_rss=new Rss_item();
		}else if("title".equals(qName)){
			title=true;
			sb=new StringBuffer();
		}else if("link".equals(qName)){
			link=true;
		}else if("description".equals(qName)){
			des=true;
		}else if("pubDate".equals(qName)){
			pub=true;
		}
	}

	
}
